package com.fowo.api.sys.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.fowo.api.sys.model.SysAreaVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.sys.entity.SysArea;
import com.fowo.api.sys.mapper.SysAreaMapper;
import com.fowo.api.sys.model.SysAreaSearchParamPo;
import com.fowo.api.sys.service.SysAreaService;

@Service
public class SysAreaServiceImpl extends ServiceImpl<SysAreaMapper, SysArea> implements SysAreaService {

    @Override
    public List<SysArea> search(SysAreaSearchParamPo search) {
        return baseMapper.search(search);
    }

    @Override
    public List<SysAreaVo> tree(SysAreaSearchParamPo searchParam) {
        List<SysArea> list = search(searchParam);
        List<SysAreaVo> tree = new ArrayList<>();
        buildTree(tree, list, null);
        return tree;
    }

    private void buildTree(List<SysAreaVo> tree, List<SysArea> list, Long parentId) {
        for (SysArea sysArea : list) {
            if (Objects.equals(sysArea.getParentId(), parentId)) {
                SysAreaVo vo = new SysAreaVo();
                BeanUtils.copyProperties(sysArea, vo);
                tree.add(vo);

                List<SysAreaVo> children = new ArrayList<>();
                buildTree(children, list, sysArea.getId());
                if (!children.isEmpty()) {
                    vo.setChildren(children);
                }
            }
        }
    }

    @Override
    public Long getIdByName(String name) {
        return baseMapper.getIdByName(name);
    }
    
}
